package _interview100;

import java.util.List;

/**
 * 139. 单词拆分
 */
public class No139 {
    private String s;
    private List<String> wordDict;

    /**
     * 1. 递归
     */
    public boolean wordBreak1(String s, List<String> wordDict) {
        this.s = s;
        this.wordDict = wordDict;
        int n = s.length();
        return dfs(n);
    }

    private boolean dfs(int i) {
        for (int j = i - 1; j >= 0; j--) {
            if (wordDict.contains(s.substring(j, i)) && dfs(j)) return true;
        }
        return i == 0;
    }

    /**
     * 2. 迭代
     */
    public boolean wordBreak2(String s, List<String> wordDict) {
        int n = s.length();
        boolean[] f = new boolean[n + 1];
        label:
        for (int i = 0; i <= n; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (wordDict.contains(s.substring(j, i)) && f[j]) {
                    f[i] = true;
                    continue label;
                }
            }
            f[i] = i == 0;
        }
        return f[n];
    }
}
